package com.solarStruggle.graphics

import java.awt.{Color}
import util.{Vector2D}

/**
 * A wrapped image generator takes a base image and wraps onto a map.
 *
 * <p>The map image acts kind of like a height map.  For each point in the image,
 * a gradient vector is calculated.  This is calculated by looking at each of
 * the surrounding pixels, and multiplying a unit vector pointing from the
 * center of the current pixel to the center of the surrounding pixel by the
 * magnitude of the difference in color between the two.</p>
 *
 *
 *
 */
class WrappedImageGenerator(baseImage: BufferedImage, mapImage: BufferedImage, maxDelta: Int, fill: Color, squareSize: Int)
extends ProceduralImageGenerator(baseImage.getWidth, baseImage.getHeight, fill, squareSize) {
 
  private def getColorAbs(c: Color): Double = 
    (c.getRed.toDouble / 255.0 +
     c.getGreen.toDouble / 255.0 +
     c.getBlue.toDouble / 255.0) / 3.0

  override def renderPixel(image: BufferedImage, x: Int, y: Int) {
    
    val centerColor = getColorAbs(mapImage.getPixel(x, y))
    
    if(centerColor > 0.001) {
    
      var gradientVector = new Vector2D(0, 0)
   
      for(dx <- -3 to 3; dy <- -3 to 3)
        if(dx != 0 || dy != 0)
          gradientVector += (new Vector2D(dx, dy).normalize() * (centerColor - getColorAbs(mapImage.getPixel(x + dx, y + dy))))

      gradientVector = gradientVector.normalize()
    
      image.setPixel(x, y, baseImage.getPixel(
        x + ((1.0 - centerColor) * maxDelta * gradientVector.dx).toInt,
        y + ((1.0 - centerColor) * maxDelta * gradientVector.dy).toInt))
    }
  }
}
